<?php
function sort_by($array,  $keyname = null, $sortby='asc') {
    $myarray = $inarray = array();
    # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
    # Sort the new array by
    switch ($sortby) {
        case 'asc':
        # Sort an array and maintain index association...
            asort($myarray);
            break;
        case 'desc':
        case 'arsort':
        # Sort an array in reverse order and maintain index association
            arsort($myarray);
            break;
        case 'natcasesor':
        # Sort an array using a case insensitive "natural order" algorithm
            natcasesort($myarray);
            break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key=> $befree) {
        $inarray[] = $array[$key];
    }
    return $inarray;
}
function parse_js_load($str) {
    return  '<script type="text/javascript" src="'.$str.'"></script>';
}

function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 +----------------------------------------------------------
 * 对查询结果集进行排序
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型 asc arsort natcaseror
 * @param array $list 查询结果
 +----------------------------------------------------------
 * @return array
 +----------------------------------------------------------
 */
function sortBy($list,$field, $sortby='asc' ) {
    if(is_array($list)) {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ( $refer as $key=> $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/**
 +----------------------------------------------------------
 * 在数据列表中搜索
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param mixed $condition 查询条件
 * 支持 array('name'=>$value) 或者 name=$value
 * @param array $list 数据列表
 +----------------------------------------------------------
 * @return array
 +----------------------------------------------------------
 */
function search($list,$condition) {
    if(is_string($condition))
        parse_str($condition,$condition);
    // 返回的结果集合
    $resultSet = array();
    foreach ($list as $key=>$data) {
        $find   =   false;
        foreach ($condition as $field=>$value) {
            if(isset($data[$field])) {
                if(0 === strpos($value,'/')) {
                    $find   =   preg_match($value,$data[$field]);
                }elseif($data[$field]==$value) {
                    $find = true;
                }
            }
        }
        if($find)
            $resultSet[]     =   &$list[$key];
    }
    return $resultSet;
}

/**
 +----------------------------------------------------------
 * 压缩PHP文件内容和简单加密
 +----------------------------------------------------------
 * @param string $filename 文件名
 * @param boolean $strip 是否去除代码空白和注释
 +----------------------------------------------------------
 * @return false|integer 返回加密文件的字节大小
 +----------------------------------------------------------
 */
function encode_file_contents($filename,$strip=true) {
    $type = strtolower(substr(strrchr($filename, '.'),1));
    if('php'==$type && is_file($filename) && is_writeable($filename)) {
        // 如果是PHP文件 并且可写 则进行压缩
        $contents  =  file_get_contents($filename);
        // 判断文件是否已经被加密
        $pos = strpos($contents,'/*Protected by Think Cryptation*/');
        if( false === $pos  || $pos>100 ) {
            if($strip) {
                // 去除PHP文件注释和空白，减少文件大小
                $contents  =  php_strip_whitespace($filename);
            }
            // 去除PHP头部和尾部标识
            $headerPos   =  strpos($contents,'<?php');
            $footerPos    =  strrpos($contents,'?>');
            $contents  =  substr($contents,$headerPos+5,$footerPos-$headerPos);
            // 对文件内容进行加密存储
            $encode   =  base64_encode(gzdeflate($contents));
            $encode   = '<?php'." /*Protected by Think Cryptation*/\n\$cryptCode='".$encode."';eval(gzinflate(base64_decode(\$cryptCode)));\n /*Reverse engineering is illegal and strictly prohibited - (C) Think Cryptation 2006*/\n?>";
            // 重新写入加密内容
            return file_put_contents($filename,$encode);
        }
    }
    return false;
}

/**
 +----------------------------------------------------------
 * 压缩文件夹下面的PHP文件
 +----------------------------------------------------------
 * @param string $path 路径
 +----------------------------------------------------------
 * @return void
 +----------------------------------------------------------
 */
function encode_dir($path) {
    if(substr($path, -1) != "/")    $path .= "/";
    $dir=glob($path."*");
    foreach($dir as $key=>$val) {
        if(is_dir($val)) {
            encode_dir($val);
        } else {
            encode_file_contents($val);
        }
    }
}

function RemoveXSS($val) {
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <java\0script>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=@avascript:alert('XSS')>
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

        // @ @ search for the hex values
        $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
    }

    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);

    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }
    return $val;
}

function text2wml($content) {
    // 将 WML 变量前缀"$"转义
    $content = str_replace('$', '$$', $content);
    // 转换特殊字符，并将 Windows/DOS 换行符（\r\n）转化为 Unix 换行符（\n）
    $content = str_replace("\r\n", "\n", htmlspecialchars($content));
    // 通过换行符来将各行分开进行处理（过滤空行）
    $content = explode("\n", $content);
    for ($i = 0; $i < count($content); $i++) {
        // 过滤首尾空格
        $content[$i] = trim($content[$i]);
        // 如果去掉全角空格为空行，则设为空行，否则不对全角空格过滤。
        if (str_replace("　", "", $content[$i]) == "") $content[$i] = "";
    }
    //合并各行，转化为 WML，并过滤掉空行
    $content = str_replace("<p><br /></p>\n", "", "<p>".implode("<br /></p>\n<p>", $content)."<br /></p>\n");
    return $content;
}

function html2wml($content) {
    // 过滤掉样式表和脚本
    $content = preg_replace("/<style .*?<\/style>/is", "", $content);
    $content = preg_replace("/<script .*?<\/script>/is", "", $content);
    // 首先将各种可以引起换行的标签（如<br />、<p> 之类）替换成换行符"\n"
    $content = preg_replace("/<br\s*\/?>/i", "\n", $content);
    $content = preg_replace("/<\/?p>/i", "\n", $content);
    $content = preg_replace("/<\/?td>/i", "\n", $content);
    $content = preg_replace("/<\/?div>/i", "\n", $content);
    $content = preg_replace("/<\/?blockquote>/i", "\n", $content);
    $content = preg_replace("/<\/?li>/i", "\n", $content);
    // 将"&nbsp;"替换为空格
    $content = preg_replace("/\&nbsp\;/i", " ", $content);
    // 某些不规范的网页中可能有"&nbsp"，在普通网页中显示会按照"&nbsp;"显示，不会引起错误，但是在 WAP 中会原样显示，因此也要替换成空格。
    $content = preg_replace("/\&nbsp/i", " ", $content);
    // 过滤掉剩下的 HTML 标签
    $content = strip_tags($content);
    // 将 HTML 中的实体（entity）转化为它所对应的字符（WML 仅支持很有现的几个 entity），这里我转化的是中文网页，因此我指定了"GB2312"编码。
    $content = html_entity_decode($content, ENT_QUOTES, "GB2312");
    // 过滤掉不能转化的实体（entity）
    $content = preg_replace("/\&\#.*?\;/i", "", $content);

    // 上面是将 HTML 网页内容转化为带换行的纯文本，下面是将这些纯文本转化为 WML。
    return text2wml($content);
}

/**
 *获取表的全名
 */
function table($tname) {
    return '`'.C('DB_PREFIX').$tname.'` ';
}
function toDate($time,$formate='Y-m-d H:i') {
    $time = $time?$time:time();
    return date($formate,$time);
}

/**
 * 得到当前页面的url
 * @return <type>
 */
function cur_absolute_url() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

/**
 * 字符串截取
 */
function bb_substr($str, $width, $start=0, $suff='...', $encoding='utf8') {
    $str = mb_strimwidth($str, $start, $width, $suff, $encoding);
    return $str;
}
/**
 * cookie 和session
 */
function CS($key,$value) {
    if(!empty($value)) {
        $value = serialize($value);
    }
    if(C('COOKIE_OR_SESSION')) {
        if(empty($value)) {
            return $_COOKIE[$key]?unserialize($_COOKIE[$key]):null;
        }else {
            setcookie($key,$value);
        }
    }else {
        if(empty($value)) {
            return $_SESSION[$key]?unserialize($_SESSION[$key]):null;
        }else {
            $_SESSION[$key] = $value;
        }
    }
    return true;
}
?>